const CacheObj = require('../plugins/global-cache')

export default function(req, res, next) {
  let pathname = req._parsedOriginalUrl.pathname
  console.log('middleware-page-cache:path', pathname)
  // console.log('middleware-page-cache:req', req)
  // console.log('middleware-page-cache:res', res)
  // 经过路由判断，只有首页才进行缓存
  // if (['/about'].indexOf(pathname) > -1) {
  let cacheKey = 'page-cache:' + pathname
  const existsHtml = CacheObj.get(cacheKey)
  if (existsHtml) {
    console.log('===HTML===Exists===')
    return res.end(existsHtml.html, 'utf-8')
  } else {
    res.original_end = res.end
    // 重写res.end
    res.end = function(data) {
      console.log('===HTML-statusCode===', res.statusCode)
      if (res.statusCode === 200) {
        // 设置缓存
        CacheObj.set(cacheKey, {
          html: data
        })
        console.log('===HTML===CacheSet-OK===')
      }
      // 最终返回结果
      res.original_end(data, 'utf-8')
    }
  }


  // }

  next()
}
